<?php

namespace App\Http\Controllers;

use App\Post;
use App\PostComment;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, Post $model)
    {
        if (!is_null($request->type) && !in_array($request->type, [0, 1]))
            return redirect()->route('post.index')->withStatus('请选择正确的分类');

        if (is_null($request->search))
            // 按分类查看列表
            $posts = is_null($request->type)
                ? $model->withCount('comments')
                    ->paginate(15)
                : $model->withCount('comments')
                    ->where('status', $request->type)
                    ->paginate(15);
        else
            // 搜索
            $posts = $model->withCount('comments')
//                ->where('status', 1)
//                ->whereIn('rec_status', [1, 2])
                ->where('content', 'like', "%{$request->search}%")
                ->paginate(15);

        return view('posts.index', [
            'posts' => $posts,
            'countAll' => $model->count(),
            'countStatus0' => $model->where('status', 0)->count(),
            'countStatus1' => $model->where('status', 1)->count(),
        ]);
    }

    /**
     * @param  \Illuminate\Http\Request  $request
     * @param \App\Post $post
     * @return \Illuminate\Http\Response
     */
    public function status(Request $request, Post $post)
    {
        $post->status = $request->get('status');
        $post->save();
        return response(json_encode((object)[
            'status' => $post->status,
            'updated_at' => $post->updated_at->toDateTimeString()
        ]));
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param \App\Post $post
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, Post $post)
    {
        return view('posts.show', [
            'post' => $post->loadCount('comments')->loadMissing(['comments', 'comments.user:id,username'])
        ]);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param \App\Post $post
     * @param \App\PostComment $comment
     * @return \Illuminate\Http\Response
     */
    public function commentStatus(Request $request, Post $post, PostComment $comment)
    {
        $comment->status = $request->get('status');
        $comment->save();
        return response(json_encode((object)[
            'status' => $comment->status
        ]));
    }
}
